package com.mbiolance.cloud.activiti.controller;


import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Controller
@Slf4j
@RequestMapping("/activiti-explorer/service")
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 创建流程定义
     */
    @RequestMapping(value = "/create")
    public void create(HttpServletResponse response) throws IOException {
        String id = "";
        String name = "mbiolance cloud process";
        String description = "mbiolance cloud process";
        String key = RandomUtil.randomString(11);
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.set("stencilset", stencilSetNode);
        Model modelData = this.repositoryService.newModel();
        ObjectNode modelObjectNode = objectMapper.createObjectNode();
        modelObjectNode.put("name", name);
        modelObjectNode.put("revision", 1);
        description = StringUtils.defaultString(description);
        modelObjectNode.put("description", description);
        modelData.setMetaInfo(modelObjectNode.toString());
        modelData.setName(name);
        modelData.setKey(StringUtils.defaultString(key));
        this.repositoryService.saveModel(modelData);
        this.repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes(StandardCharsets.UTF_8));
        id = modelData.getId();
        log.info("ActivitiController create new process, modelId: {}", id);
        response.sendRedirect("/modeler.html?modelId=" + id);
    }

}
